package com.isoftstone.framework.shiro;

import com.isoftstone.common.BusinessException;
import com.isoftstone.common.utils.JsonUtil;
import com.isoftstone.framework.domain.Tidings;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
public final class TELAuthenticationFilter extends AuthenticatingFilter {

    protected static final String AUTHORIZATION_HEADER = "userid";

    public TELAuthenticationFilter() {
    }

    @Override
    public void setLoginUrl(String loginUrl) {
        String previous = getLoginUrl();
        if (previous != null) {
            this.appliedPaths.remove(previous);
        }
        super.setLoginUrl(loginUrl);
        this.appliedPaths.put(getLoginUrl(), null);
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        boolean loggedIn = false;
        HttpServletRequest res = (HttpServletRequest) request;

        if(StringUtils.equals("/tel/getJsapiTicket",res.getServletPath())){
            return true;
        }
        if(StringUtils.equals("/tel/getLoginUserId",res.getServletPath())){
            return true;
        }
        Subject subject = this.getSubject(request, response);
        boolean authenticated = subject.isAuthenticated();
        if(authenticated){
            return true;
        }

        if (isLoginRequest(request, response) || isLoggedAttempt(request, response)) {
            loggedIn = executeLogin(request, response);
        }else{
            PrintWriter writer = getWriterFromResponse(response);
            writer.print(JsonUtil.beanToJson(Tidings.error("userid is null", "Unauthorized")));
        }

//        //没有登陆返回401
//        if (!loggedIn) {
//            PrintWriter writer = getWriterFromResponse(response);
//            writer.print(JsonUtil.beanToJson(new Tidings<>(false, "Unauthorized", "Unauthorized")));
//        }

        return loggedIn;
    }

    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        TELAuthenticationToken token = this.createToken(request, response);

        try {
            Subject subject = this.getSubject(request, response);

            subject.login(token);
            return this.onLoginSuccess(token, subject, request, response);
        } catch (AuthenticationException var5) {
            return this.onLoginFailure(token, var5, request, response);
        }
    }
    /**
     * 对跨域提供支持
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
       // httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }

    @Override
    protected TELAuthenticationToken createToken(ServletRequest request, ServletResponse response) throws IOException {
        String userid = getAuthzHeader(request);
        return new TELAuthenticationToken(userid,userid);

    }

    public PrintWriter getWriterFromResponse(ServletResponse res){
        HttpServletResponse response = (HttpServletResponse)res;
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

        try {
            return response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessException(e.getMessage());
        }

    }

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        log.info("登录失败",e);
        PrintWriter writer = getWriterFromResponse(response);
        writer.print(JsonUtil.beanToJson(Tidings.error( "Unauthorized", "Unauthorized")));
        return false;

    }

    protected boolean isLoggedAttempt(ServletRequest request, ServletResponse response) {
        String authzHeader = getAuthzHeader(request);
        return authzHeader != null;
    }

    protected String getAuthzHeader(ServletRequest request) {
        HttpServletRequest httpRequest = WebUtils.toHttp(request);
        return httpRequest.getHeader(AUTHORIZATION_HEADER);
    }


}
